<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.NickName" placeholder="登录名" style="width: 200px;" class="filter-item" clearable
        @keyup.enter.native="handleFilter" />

      <el-select v-model="listQuery.Status" style="width: 140px" class="filter-item" clearable>
        <el-option v-for="item in sortOptions" :key="item.Key" :label="item.Value" :value="item.Key" />
      </el-select>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
        @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
      style="width: 100%;">
      <!-- 添加模板列显示序号 -->
      <el-table-column type="index" label="序号" width="50" align="center">
        <!-- 可以通过传递row和index来自定义序号的显示格式 -->
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="登录名" prop="UserName" align="center">
        <template slot-scope="{row}">
          <span>{{ row.登录名 }}</span>
        </template>
      </el-table-column>

      <el-table-column label="姓名" prop="UserName" align="center">
        <template slot-scope="{row}">
          <span>{{ row.用户姓名 }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户状态" prop="UserName" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.用户状态" :style="{
            color:
              row.用户状态 == '冻结中'
                ? '#F56C6C'
                : '#67C23A',
          }">
            {{ row.用户状态 }}
          </el-tag>
        </template>
      </el-table-column>



      <el-table-column label="联系手机" prop="UserName" align="center">
        <template slot-scope="{row}">
          <span>{{ row.联系手机 }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>

          <el-button v-if="row.用户状态 != '冻结中'" size="mini" @click="handleModifyStatus(row, '冻结中')">
            禁用
          </el-button>
          <el-button v-if="row.用户状态 == '冻结中'" size="mini" type="success" @click="handleModifyStatus(row, '使用中')">
            启用
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page-sizes="[10, 20, 30]" :page-size="10"
      layout="total, sizes, prev, pager, next, jumper" :page.sync="listQuery.PageIndex" :limit.sync="listQuery.PageSize"
      @pagination="getList" />



    <!-- 编辑添加 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="80px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="登录名" prop="登录名">
          <el-input v-model="temp.登录名" />
        </el-form-item>

        <el-form-item label="用户姓名" prop="用户姓名">
          <el-input v-model="temp.用户姓名" />
        </el-form-item>
        <el-form-item label="联系手机" prop="联系手机">
          <el-input v-model="temp.联系手机" />
        </el-form-item>
        <el-form-item label="用户状态" prop="用户状态">
          <el-select v-model="temp.用户状态" style="width: 240px" class="filter-item">
            <el-option v-for="item in sortOptions" :key="item.Key" :label="item.Value" :value="item.Key" />
          </el-select>
        </el-form-item>

        <el-form-item label="用户角色" prop="用户角色">
          <el-select v-model="temp.用户角色" style="width:240px;" multiple placeholder="请选择">
            <el-option v-for="item in roleOptions" :key="item.角色编号" :label="item.角色名称" :value="item.角色编号" />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus == '新增' ? createUser() : updateUserData()">
          提交
        </el-button>
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>
  </div>



</template>

<script>
import { getUserList, addUser, updateUser, getStatusList,getRolesList ,getUserModel} from '@/api/user'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import waves from '@/directive/waves' // waves directive
export default {
  name: 'userList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const checkUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('登录名不能为空'))
      }
      if (value.length < 6) {
        return callback(new Error('登录名不能小于6位'))
      }
      callback()
    }
    return {
      tableKey: 0,
      dialogFormVisible: false,
      dialogStatus: '',
      list: null,
      total: 0,
      sortOptions: null,
      roleOptions: null,
      listLoading: true,
      textMap: ['编辑', '新增'],
      listQuery: {
        PageIndex: 1,
        PageSize: 10,
        NickName: '',
        Status: ''
      },
     
      temp: {
        用户编号: '',
        登录名: '',
        用户姓名: '',
        联系手机: '',
        用户状态: '',
        用户角色: ''
      },
      rules: {
        登录名: [{ required: true, trigger: 'change', validator: checkUserName }],
        用户姓名: [{ required: true, message: '用户姓名不能为空', trigger: 'change' }],
        用户状态: [{ required: true, message: '用户状态不能为空', trigger: 'change' }],
        用户角色: [{ required: true, message: '用户角色不能为空', trigger: 'change' }]
      },
    }
  },

  created() {
    this.getStatusDrop()
    this.getRolesDrop()
    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        用户编号: '',
        登录名: '',
        用户姓名: '',
        联系手机: '',
        用户状态: '',
        用户角色: ''
      }
    },
    getList() {
      this.listLoading = true
      getUserList(this.listQuery).then(response => {
        console.log(response)
        this.list = response.data.Rows
        this.total = response.data.Records
        // Just to simulate the time of the request
        this.listLoading = false

      })
    },
    getStatusDrop() {
      getStatusList(this.listQuery).then(response => {
        console.log(response)
        this.sortOptions = response.data
        // this.sortOptions = Object.assign({}, response.data) // copy obj
      })
    },
    getRolesDrop() {
      getRolesList({PageIndex:1,PageSize:999}).then(response => {
        console.log(response)
        this.roleOptions = response.data.Rows
        // this.sortOptions = Object.assign({}, response.data) // copy obj
      })
    },
    handleModifyStatus(row, status) {
      updateUser({ 用户编号: row.用户编号, 用户状态: status }).then(response => {
        const index = this.list.findIndex(v => v.用户编号 === this.temp.用户编号)
        this.list.splice(index, 1, this.temp)
        this.dialogFormVisible = false
        this.$message({
          message: response.msg,
          type: response.code = "200" ? 'success' : 'error',
        })
        row.用户状态 = status
      })

    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = '新增'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createUser() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addUser(this.temp).then(response => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: response.msg,
              type: response.code = "200" ? 'success' : 'error',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      getUserModel({UserId:row.用户编号}).then(response => {
        this.temp = Object.assign({}, row) // copy obj
      this.temp.用户编号 = row.用户编号
      this.temp.用户角色= response.data.RoleList
      this.dialogStatus = '更新'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      })
  
    },
    updateUserData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUser(tempData).then(response => {
            const index = this.list.findIndex(v => v.用户编号 === this.temp.用户编号)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: response.msg,
              type: response.code = "200" ? 'success' : 'error',
              duration: 2000
            })
          })
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    }

  },



}
</script>
